package net.kleinhenz.droidshop;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import net.kleinhenz.droidshop.R;
import net.kleinhenz.droidshop.model.Price;
import net.kleinhenz.droidshop.model.Product;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class PricesActivity extends ListActivity implements ListAdapter
{
	public static int MENUITEM_DELETEALL = 0;
	public static int MENUITEM_ABOUT = 1;
	public static int MENUITEM_SHARE = 2;

	private Product product = null;
	private List<Price> prices = null; 

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);

		product = (Product)getIntent().getExtras().getSerializable("product");
		prices = product.getPrices();

		if (prices.isEmpty())
			new AlertDialog.Builder(this)
				.setTitle(getResources().getString(R.string.warning))
				.setMessage(getResources().getString(R.string.list_empty))
				.setPositiveButton(R.string.back, new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();						
					}
				})
				.show();
		
		getListView().setPadding(5, 5, 5, 5);
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		registerForContextMenu(getListView());
		setListAdapter(this);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{
		openItem(prices.get(position));
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		return getParent().onMenuItemSelected(featureId, item);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		LinearLayout layout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.productentry, null, false);
		Price thisPrice = product.getPrices().get(position);
		
		TextView merchantView = (TextView)layout.findViewById(R.id.Merchant);
		TextView priceView = (TextView)layout.findViewById(R.id.Price);
		TextView availabilityView = (TextView)layout.findViewById(R.id.Availability);

		ImageView logoView = (ImageView)layout.findViewById(R.id.AmazonLogo);
		if (thisPrice.getMerchant().equalsIgnoreCase("amazon.com"))
		{
			logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazoncom));
			((LinearLayout)layout.findViewById(R.id.MerchantImage)).removeView(merchantView);
		}
		else if (thisPrice.getMerchant().equalsIgnoreCase("amazon.co.uk"))
		{
			logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazoncouk));
			((LinearLayout)layout.findViewById(R.id.MerchantImage)).removeView(merchantView);
		}
		else if (thisPrice.getMerchant().equalsIgnoreCase("amazon.de"))
		{
			logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazonde));
			((LinearLayout)layout.findViewById(R.id.MerchantImage)).removeView(merchantView);
		}
		else 
		{
			logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazonmarket));
			merchantView.setText(thisPrice.getMerchant().length()>25?thisPrice.getMerchant().substring(0, 25):thisPrice.getMerchant());
		}

		priceView.setText(createPriceString(thisPrice.getFormattedPrice(), getResources().getString(R.string.locale)));
		availabilityView.setText(thisPrice.getAvailability().trim());
		
		return layout;
	}
	
	@Override
	public int getItemViewType(int position) 
	{
		return 0;
	}

	@Override
	public int getViewTypeCount() 
	{
		return 1;
	}

	@Override
	public Object getItem(int position) 
	{
		return prices.get(position);
	}

	@Override
	public boolean areAllItemsEnabled() 
	{
		return true;
	}

	@Override
	public boolean isEnabled(int position) 
	{
		return true;
	}

	@Override
	public int getCount() 
	{
		return prices.size();
	}

	@Override
	public long getItemId(int position) 
	{
		return position;
	}

	@Override
	public boolean hasStableIds() 
	{
		return true;
	}

	@Override
	public boolean isEmpty() 
	{
		return prices.isEmpty();
	}

	@Override
	public void registerDataSetObserver(DataSetObserver observer)
	{
		// NOP
	}

	@Override
	public void unregisterDataSetObserver(DataSetObserver observer)
	{
		// NOP
	}
	
	public static String createPriceString(String formattedPrice, String locale)
	{
		Map<String, Double> currencyMap = DroidShop.currency;
		
		if (currencyMap.isEmpty() || !currencyMap.containsKey("USD") || !currencyMap.containsKey("GBP"))
			return formattedPrice;
		
		String valueStr = formattedPrice.replaceAll("[^0-9]*([0-9]{1,2}[.,][0-9]{1,2})[^0-9]*", "$1");
		String currency = formattedPrice.replaceAll("([^0-9]*)[0-9]{1,2}[.,][0-9]{1,2}([^0-9]*)", "$1 $2");
		double value = Double.parseDouble(valueStr.replace(',', '.'));

		double euroUsd = DroidShop.currency.get("USD");
		double euroGbp = DroidShop.currency.get("GBP");
		
		DecimalFormat format = new DecimalFormat("00.00");
		
		// FIXME: externalize locale strings
		// FIXME: this is mostly a broken hack, modify xml to include canonical values
		if (locale.equals("DE") && currency.contains("€"))
		{
			return formattedPrice;
		}
		else if (locale.equals("DE") && currency.contains("$"))
		{
			return formattedPrice + " (€ " + format.format(value/euroUsd) + ")";
		}
		else if (locale.equals("DE") && currency.contains("£"))
		{
			return formattedPrice + " (€ " + format.format(value/euroGbp) + ")";			
		}
		if (locale.equals("UK") && currency.contains("£"))
		{
			return formattedPrice;
		}
		else if (locale.equals("UK") && currency.contains("$"))
		{
			return formattedPrice + " (£ " + format.format((value/euroUsd)*euroGbp) + ")";			
		}
		else if (locale.equals("UK") && currency.contains("€"))
		{
			return formattedPrice + " (£ " + format.format(value*euroGbp) + ")";			
		}
		if (locale.equals("US") && currency.contains("$"))
		{
			return formattedPrice;
		}
		else if (locale.equals("US") && currency.contains("£"))
		{
			return formattedPrice + " ($ " + format.format((value/euroGbp)*euroUsd) + ")";	
		}
		else if (locale.equals("US") && currency.contains("€"))
		{
			return formattedPrice + " ($ " + format.format(euroUsd) + ")";	
		}
		
		return null;
	}	
	
	private void openItem(Price item) 
	{		
		Uri uri = Uri.parse(item.getBuyLink().toString());
		startActivity(new Intent(Intent.ACTION_VIEW, uri)); 
	}	
}
